using System;
using System.Linq;
using System.Threading.Tasks;
using SuperSocket;

namespace FixedHeaderSample.WebSocketServer.Server
{
    public class MyMiddleware : MiddlewareBase
    {
        private ISessionContainer _sessionContainer;
        private Task _sendTask;
        private bool _stopped;

        public override void Start(IServer server)
        {
            _sessionContainer = server.GetSessionContainer();
            _sendTask = RunAsync(); //模拟消息推送
        }

        private async Task RunAsync()
        {
            while (!_stopped)
            {
                var sent = await Push();

                if (sent == 0 && !_stopped)
                {
                    await Task.Delay(1000 * 5);
                }
                else
                {
                    await Task.Delay(1000 * 2);
                }
            }
        }

        private async ValueTask<int> Push()
        {
            if (_sessionContainer == null)
            {
                return 0;
            }

            // about 300 characters
            var line = string.Join("-", Enumerable.Range(0, 10).Select(x => Guid.NewGuid().ToString()));
            var count = 0;

            foreach (var s in _sessionContainer.GetSessions<MyWebSocketSession>())
            {
                await s.SendAsync(line);
                count++;

                if (_stopped)
                    break;
            }

            return count;
        }

        public override void Shutdown(IServer server)
        {
            _stopped = true;
            _sendTask.Wait();

            foreach (var s in _sessionContainer.GetSessions<MyWebSocketSession>())
            {
                s.PrintStats();
            }
        }
    }
}
